package net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Vector;

public class TCP_ServerClient extends Thread
{
	private Socket clientSocket=null;
	
	private Vector<TCP_Message> Inbox = new Vector<TCP_Message>();
	
	private PrintWriter out=null;
	private BufferedReader in=null;
	
	public TCP_ServerClient(Socket client)
	{
		clientSocket=client;
		try
		{
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader( new InputStreamReader( clientSocket.getInputStream()) );
		} catch (IOException e)
		{
			System.out.println("Temporal client exception: "+e.getMessage());
		}
	}
	public void run()
	{
		String msg[], Input;
		Inbox.clear();
		try 
		{ 	 			
			while (!clientSocket.isClosed()) 
			{ 
				Input = in.readLine();
				if(Input==null)
				{
					Inbox.add(new TCP_Message("NET_ER", "end of stream reached"));
					return;
				}
				msg = Input.split("\\|",2);
				if(msg.length==2)
					Inbox.add(new TCP_Message(msg[0],msg[1]));
				else
					System.out.println("Message format is wrong. Source = temp.");
			} 
			return;
		}
		catch (IOException e) 
		{ 
			Inbox.add(new TCP_Message("SYS_EX",e.getMessage()));
		}
		Inbox.add(new TCP_Message("NET_ER","connection lost"));
	}
	
	public void closeConnection()
	{
		try
		{
			clientSocket.close();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public TCP_Message getMessage()
	{
		if(Inbox.isEmpty())
			return null;
		else
		{
			TCP_Message msg = Inbox.get(0);
			Inbox.remove(0);
			return msg;
		}	
	}
	
	public void SendMessage(String cmd, String data)
	{
		out.println(cmd+"|"+data);
	}
}
